<template>
    <div class="top">
        <input type="text" v-model="keyword">
        <input type="button" value="查找" @click="filterBook">
        <h2>图书列表</h2>
        <input type="button" value="新增" @click="addBook">
    </div>
    <div class="content">
        <table>
            <thead>
                <tr>
                    <th>序号</th>
                    <th>书名</th>
                    <th>作者</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in bookList" :key="item.id">
                    <td>{{ item.id }}</td>
                    <td>{{ item.name }}</td>
                    <td>{{ item.author }}</td>
                    <td>
                        <input type="button" value="编辑" @click="updateBook(item.id)">
                        <input type="button" value="删除" @click="delBook(item.id)">
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { bookAll,bookDel } from '@/bookApi/bookApi'
import { useRouter } from 'vue-router'

let bookList = ref([])
let keyword = ref('')
let router = new useRouter()

async function delBook(id){
    if(confirm(`确定要删除 id 为 ${id} 的图书数据吗？`)){
        await bookDel(id)
        bookList.value = bookList.value.filter(item => item.id !== id)
    }
}

function addBook (){
    router.push('/addorupdate')
}

function updateBook (id){
    router.push(`/addorupdate/${id}`)
}

async function filterBook(){
    bookList.value = await bookAll(keyword.value)
}

onMounted(async () => {
    bookList.value = await bookAll()
    
})
</script>